package com.snda.dw.hiveapi.hiveapitest;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Hello world!
 *
 */
public class App {

    public static void main(String[] args) throws Exception {
        String querySQL = args[0];
        querySQL.replaceAll("'*'", "*");
        System.out.println(querySQL);
        ExecutorService es = Executors.newCachedThreadPool();
        final HiveSessionPool pool = HiveSessionPool.getInstance();
        Long sessionID = pool.generateSessionID();
        final HiveSession session = new HiveSession("dw", querySQL, sessionID);
        pool.addSession(session);
        final CountDownLatch counter = new CountDownLatch(2);
        final Object[] results = new Object[1];
        es.execute(new Runnable() {

            public void run() {
                try {
                    HiveQueryResult result = session.getResult();
                    results[0] = result;
                } finally {
                    counter.countDown();
                    pool.releaseSession(session);
                }
            }
        });
        es.execute(new Runnable() {

            public void run() {
                try {
                    while (true) {
                        int process = session.getProcessPercentage();
                        System.out.println(process);
                        if (process == 100) {
                            break;
                        }
                        TimeUnit.SECONDS.sleep(1);
                    }
                } catch (InterruptedException ex) {
                    Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    counter.countDown();
                }
            }
        });
        es.shutdown();
        counter.await();
        HiveQueryResult result = (HiveQueryResult) results[0];
        if (result.getErrorMessage() == null) {
            List<String> columnNames = result.getColumnNames();
            for (String columnName : columnNames) {
                System.out.print(columnName + "\t");
            }
            System.out.println("\n****************************************");
            List<List<String>> rows = result.getRows();
            for (List<String> row : rows) {
                for (String column : row) {
                    System.out.print(column + "\t");
                }
                System.out.println();
            }
        } else {
            System.out.println(result.getErrorMessage());
        }
    }
}
